import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { translateDataObject, translateDataField } from '../utils/i18nDataTranslator';

/**
 * 通用的数据国际化 Hook
 * @param rawData - 原始数据（未翻译的）
 * @param fieldsToTranslate - 需要翻译的字段配置 { fieldName: fieldType }
 * @param namespace - i18n 命名空间
 * @returns 翻译后的数据
 */
export function useDataTranslation<T extends Record<string, any>>(
  rawData: T[],
  fieldsToTranslate: Record<string, string>,
  namespace: string
): T[] {
  const { t, i18n } = useTranslation(namespace);
  const [translatedData, setTranslatedData] = useState<T[]>([]);

  useEffect(() => {
    if (rawData.length > 0) {
      const translated = translateDataObject(rawData, fieldsToTranslate, t, namespace) as T[];
      setTranslatedData(translated);
    } else {
      setTranslatedData([]);
    }
  }, [rawData, i18n.language, fieldsToTranslate, namespace, t]);

  return translatedData;
}

/**
 * 单个字段翻译 Hook
 */
export function useFieldTranslation(
  value: string | number | undefined | null,
  fieldType: string,
  namespace: string
): string {
  const { t } = useTranslation(namespace);
  
  if (!value) return '';
  
  return translateDataField(value, fieldType, t, namespace);
}

